package io.renren.controller;

import io.renren.common.utils.RedisUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@EnableScheduling
@Component
public class TaskGame {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	RedisUtils redisUtils;

	@Value("${renren.redis.open}")
	boolean open;

	/**
	 * 读取并转发其它服务器的websocket消息(集群时使用,单机可忽略)
	 */
	@Scheduled(fixedDelay = 1000)
	public void broadcastTask() {
		if (!open) {
			return;
		}
		Set<String> keys = redisUtils.keys(WebSocketRoom.UID + "_msg_*");
		for (String key : keys) {
			String json = redisUtils.get(key, 0);// 读取以后立即过期
			if (json == null || json.isEmpty()) {
				continue;
			}
			String[] array = json.split("@");
			WebSocketRoom.broadcast(Long.valueOf(array[0]), array[1]);
		}
	}

	/**
	 * 每隔一段时间来检查在线服务器(集群时使用,单机可忽略)
	 */
	@SuppressWarnings("unchecked")
	@Scheduled(initialDelay = 0, fixedDelay = 60000)
	public void checkServerTask() {
		if (!open) {
			return;
		}
		long millis = System.currentTimeMillis();
		redisUtils.set("SERVER_ONLINE_" + WebSocketRoom.UID, millis);// 保持在线状态
		// 集群服务器
		boolean flag = false;
		List<String> serverList = redisUtils.get("SERVER_LIST", List.class);
		if (serverList == null) {
			serverList = new ArrayList<String>();
			serverList.add(WebSocketRoom.UID);
			flag = true;
		} else {
			if (!serverList.contains(WebSocketRoom.UID)) {
				serverList.add(WebSocketRoom.UID);
				flag = true;
			}
			if (serverList.size() > 1) {
				Iterator<String> it = serverList.iterator();
				while (it.hasNext()) {
					String lastUpdateTime = redisUtils.get("SERVER_ONLINE_" + it.next());// 3分钟未更新SERVER_ONLINE表示当前服务器掉线
					if (lastUpdateTime == null || (millis - Long.parseLong(lastUpdateTime)) > 180000) {
						it.remove();
						flag = true;
					}
				}
			}
		}

		if (flag) {
			redisUtils.set("SERVER_LIST", serverList);
			logger.info("当前在线服务器:" + serverList.size() + "台");
		}
	}
}
